<?php

spl_autoload_unregister(array('YiiBase', 'autoload'));
Yii::import('application.extensions.phpexcel.Classes.PHPExcel', true);
//$objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));

class ExcelMono {

    public $type, $game, $gameSite, $game_parent;
    public $excelArraw, $fieldArraw, $fanArray, $headerTable, $serverData = array();
    public $allEqNum = 0; //完全相同数据数量
    public $skillId = 0; //技能ID

    public function uploadFile($file, $filetempname, $type = 'gd') {
        //返回数组
        $rArray = array();
        //自己设置的上传文件存放路径
        $filePath = Yii::app()->basePath . '/import/';
        //echo $filePath;
        $str = "";
        //注意设置时区
        $time = date("y-m-d-H-i-s"); //去当前上传的时间 
        //获取上传文件的扩展名
        $extend = strrchr($file, '.');
        //
        //上传后的文件名
        $name = $time . $extend;
        $uploadfile = $filePath . $name; //上传后的文件名地址 
        //move_uploaded_file() 函数将上传的文件移动到新位置。若成功，则返回 true，否则返回 false。
        $result = move_uploaded_file($filetempname, $uploadfile); //假如上传到当前目录下
        //echo $result;
        if ($result) { //如果上传文件成功，就执行导入excel操作
            $objReader = PHPExcel_IOFactory::createReader('Excel2007'); //use excel2007 for 2007 format 
            $objPHPExcel = $objReader->load($uploadfile);

            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();           //取得总行数 
            $highestColumn = $sheet->getHighestColumn(); //取得总列数
            //$objWorksheet = $objPHPExcel->getActiveSheet();
            //$highestRow/ = $objWorksheet->getHighestRow();
            //获取字段属性

            $fields = $this->getDBField();
            $this->getFiledConcata($fields);

            $rArray['a_count'] = $highestRow;

            //导入数量
            $inCount = 0;
            $isAllow = true;
            for ($row = 1; $row <= $highestRow; $row++) {
                //处理字段对应
                $highestColumn++;
                if ($row == 1) {
                    for ($col = 'A'; $col != $highestColumn; $col++) {
                        //处理字段对应
                        //$data = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                        $address = $col . $row;
                        $data = $sheet->getCell($address)->getValue();
                        //转换数据
                        $data = is_object($data) ? $data->getPlainText() : $data;
                        if ($data != "") {
                            if ($this->fieldArraw[$data]) {
                                $this->excelArraw[] = $this->fieldArraw[$data];
                            } else {
                                $isAllow = false;
                                $str.="字段[" . $data . "]->没有对应字段，请检查模板是否对应！<br>";
                            }
                        }
                    }
                    if (empty($this->excelArraw) || !$isAllow) {
                        $str.= "<font color='red'>没有对应字段或者模板不正确，不能导入！</font>";
                        $rArray['i_count'] = 0;
                        $rArray['msg'] = $str;
                        return $rArray;
                    }
                } else {
                    $sArray = array();
                    //注意highestColumnIndex的列数索引从0开始
                    $ccount = 0;
                    for ($col = 'A'; $col != $highestColumn; $col++) {
                        //处理字段对应
                        $address = $col . $row;
                        $data = $sheet->getCell($address)->getValue();

                        //转换数据/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/
//                        if(preg_match('/\d{4}[-\/]\d{1,2}[-\/]\d{1,2}\s+(\d{1,2}:\d{1,2}:\d{1,2}){0,1}/', $data))
//                        {
//                            //将日期型转成INT
//                            $data = (int)strtotime($data);
//
//                        }
//                        else
//                        {
//                            $data = is_numeric($data) ? (float) $data : (is_object($data)?$data->getPlainText():$data);
//                        }
                        $data = is_object($data) ? $data->getPlainText() : $data;
                        if ($this->excelArraw[$ccount]) {
                            $sArray[$this->excelArraw[$ccount]] = $data;
                        }
                        $ccount++;
                    }
                    //保存数据
                    //var_dump($sArray);
                    $saveRetrun = $this->saveExcelData($sArray);
                    if ($saveRetrun == 1) {
                        $inCount++;
                    } else {
                        $str.= $saveRetrun;
                    }
                }
            }
            $rArray['i_count'] = $inCount;
            $rArray['msg'] = $str ? $str : '<h1>数据全部导入成功！</h1>';
        } else {
            $rArray['msg'] = "数据导入失败！请检查数据正确性！";
        }
        @unlink($uploadfile); //删除上传的文件
        return $rArray;
    }

    /**
     * 获取产品模型字段
     * @return array
     */
    public function getDBField() {
        $attrData = array();
        switch ($this->type) {
            case 'GOLD':
                $model = new ProductGold;
                break;
            case 'PL':
                $model = new ProductPowerleveling;
                break;
            case 'SKILL':
                $model = new ProductSkill;
                break;
            case 'SKILL_LEVEL':
                $model = new ProductSkillLevel;
                break;
            case 'GAME_SERVER':
                $model = new ProductCategory;
                break;
            default :
                $model = new ProductBase;
                $attrModel = new ProductAttribute;
                $cr = new CDbCriteria;

                $cr->compare('game_id', $this->game_parent);
                $cr->compare('product_type', $this->type);
                $cr->compare('status', 1);
                $cr->order = 'order_sort ASC';
                foreach ($attrModel->findAll($cr) as $value) {
                    $attrData[$value->id] = "{$value->name}_{$value->id}";
                }
                break;
        }
        return $model->attributeLabels() + $attrData;
    }

    /**
     * 数据入库
     */
    public function saveExcelData($data) {
        $attrs = null;
        $attrModel = new ProductAttribute;
        $attrValModel = new ProductAttributeValue;
        switch ($this->type) {
            case 'GOLD'://金币产品
                $data['gold_game'] = $this->game;
                $data['site_key'] = (string) $this->gameSite;
                $model = new ProductGold;
                $oldData = $model->findByAttributes(array(
                    'site_key' => $this->gameSite,
                    'gold_game' => $this->game,
                    'gold_name' => $data['gold_name'],
                        ));
                break;
            case 'PL'://等级代练
                $data['pl_game'] = $this->game;
                $model = new ProductPowerleveling;
                $oldData = $model->findByAttributes(array(
                    'pl_game' => $this->game,
                    'pl_level' => $data['pl_level'],
                        ));
                break;
            case 'SKILL'://技能
                $model = new ProductSkill;
                $data['game_id'] = $this->game;
                $oldData = $model->findByAttributes(array(
                    'game_id' => $this->game,
                    'skill_name' => $data['skill_name'],
                        ));
                break;
            case 'SKILL_LEVEL'://技能等级
                $model = new ProductSkillLevel;
                $data['skill_id'] = $this->skillId;

                $oldData = $model->findByAttributes(array(
                    'skill_id' => $this->skillId,
                    'skill_level' => $data['skill_level'],
                        ));
                break;
            case 'GAME_SERVER':
                $model = new ProductCategory;
                $data['parentid'] = $this->game;
                $oldData = $model->findByAttributes(array(
                    'parentid' => $this->game,
                    'title' => $data['title'],
                        ));
                break;
            default ://综合产品处理
                $model = new ProductBase;

                $data['p_game'] = $this->game;
                $data['p_type'] = $this->type;
                $oldData = $model->findByAttributes(array(
                    'p_game' => $this->game,
                    'p_type' => $this->type,
                    'p_name' => $data['p_name'],
                        ));
                break;
        }

        if ($oldData) {
            return $this->getUpdateString($data, $oldData);
        } else {
            //产品属性处理
            $model->attributes = $data;
            $attrs = $attrModel->findAllByAttributes(array(
                'product_type' => $this->type,
                'game_id' => $this->game_parent,
                    ));
            if ($model->save() && !empty($attrs)) {
                $product_id = $model->id;
                foreach ($attrs as $attr) {
                    $attrValModel->unsetAttributes();
                    $attrValModel->setIsNewRecord(true);
                    $value = '';
                    switch ($attr->input_type) {
                        case 'NUMS':
                            $rows_array = explode("\n", $data[$attr->id]);
                            $nums_array = array('num' => array(), 'unit' => array(), 'discount' => array());
                            foreach ($rows_array as $row_str) {
                                if ($row_str) {
                                    $s_array = explode('|', $row_str);
                                    $nums_array['num'][] = $s_array[0];
                                    $nums_array['unit'][] = $s_array[1];
                                    $nums_array['discount'][] = $s_array[2];
                                }
                            }
                            $value = serialize($nums_array);
                            break;
                        default:
                            $value = $data[$attr->id];
                            break;
                    }

                    $attrValModel->attributes = array(
                        'product_id' => $product_id,
                        'attribute_id' => $attr->id,
                        'attribute_value' => $value
                    );

                    if (!$attrValModel->save()) {
                        //print_r($attrValModel->errors);
                    }
                }
            }
            return true;
        }
//
//        //更新数据
//        if ($oldData) {
//            return $this->getUpdateString($data, $oldData);
//        } else {
//            $model->attributes = $data;
//            return $model->save();
//        }
    }

    /**
     * 获取更新字符
     */
    public function getUpdateString($fData, $oldData) {
        $rString = "";
        $items = "";
        $headerTable = "";
        $allEq = true;
        foreach ($fData as $key => $sData) {
            if (!$this->headerTable) {
                $headerTable.= "<th>" . $this->fanArray[$key] . "</th>";
            }
            $items .= "<td rel='" . $key . "'>" . $sData . "</td>";
            if (!is_numeric($key)) {
                if ($oldData[$key] != $sData) {
                    $allEq = FALSE;
                }
            }
        }
        if (!$allEq) {
            $rString .= $items . "<td rel='sb_hbj' nowrap><a rel='" . $oldData->id . "' href='javascript:void(null)' onclick='updateData(this)' class='update_sb'>[更新]</a></td>";
        } else {
            ++$this->allEqNum; //全等记数加1
        }

        if (!$this->headerTable) {
            $this->headerTable = true;
            $rString = "<thead><tr>" . $headerTable . "<th>操作</th></tr></thead><tr>" . $rString . "<tr>";
        } else {
            $rString = "<tr>" . $rString . "<tr>";
        }


        return $rString;
    }

    /**
     * 获取字段对应
     */
    public function getFiledConcata($fields) {
        $rArray = array();
        $fArray = array();
        foreach ($fields as $key => $sField) {
            $rArray[$sField] = $key;
            $fArray[$key] = $sField;
        }
        $this->fieldArraw = $rArray;
        $this->fanArray = $fArray;
    }

    /**
     * 判断数据
     * @param type $sData
     * @return type 
     */
    function searchServerArray($sData) {
        foreach ($this->serverData as $sArray) {
            if ($sArray['name'] == $sData) {
                return true;
            }
        }
        return false;
    }

}

?>